package cn.adolf.carmaster.ui;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import cn.adolf.carmaster.CommandActivity;
import cn.adolf.carmaster.R;
import cn.adolf.carmaster.cgutman.ui.SpinnerDialog;
import cn.adolf.carmaster.databinding.FragmentHelpBinding;
import cn.adolf.carmaster.databinding.FragmentSimpleBinding;
import cn.adolf.carmaster.helper.ToastUtil;


public class SimpleFragment extends Fragment {
    private static final String TAG = "SimpleFragment";

    private FragmentSimpleBinding binding;
    private SpinnerDialog installLoading;

    public SimpleFragment() {
        // Required empty public constructor
    }

    public static SimpleFragment newInstance() {
        SimpleFragment fragment = new SimpleFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentSimpleBinding.inflate(inflater, container, false);
        return binding.getRoot();
        // return inflater.inflate(R.layout.fragment_simple, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        intiCmdInput(view);

        initOther(view);
    }

    private void initOther(View view) {
        binding.btnReboot.setOnClickListener(v -> {
            InfoDialog dialog = new InfoDialog("重启", "是否确认重启车机？", isConfirm -> {
                if (isConfirm) {
                    doCmd("reboot");
                }
            });
            dialog.show(getActivity().getSupportFragmentManager(), "reboot");

        });

        binding.btnInstall.setOnClickListener(v -> {

            String apkPathSuffix = "/storage/usbotg/usbotg-sda1/";
            if (binding.rbApkSd.isChecked()) {
                apkPathSuffix = "/sdcard/";
            }

            String inputApkName = binding.etApkPath.getText().toString();

            if (!inputApkName.startsWith("/")) {
                inputApkName = apkPathSuffix + inputApkName;
            } else {
                ToastUtil.show("开头请不要带'/'字符");
                return;
            }

            String name = inputApkName.substring(inputApkName.lastIndexOf("/") + 1);
            if (TextUtils.isEmpty(inputApkName) || TextUtils.isEmpty(name) || ".apk".equals(name)) {
                ToastUtil.show("请输入apk名称（包括后缀）");
                return;
            }

            String suPath = "/storage/usbotg/usbotg-sda1/mtk-su";

            if (binding.rbSd.isChecked()) {
                suPath = "/sdcard/mtk-su";
            }
            String finalSuPath = suPath;
            String finalInputApkName = inputApkName;

            InfoDialog dialog = new InfoDialog("安装", "请确保所填写的路径文件存在。", isConfirm -> {
                if (isConfirm) {
                    installLoading = SpinnerDialog.displayDialog(getActivity(),
                            "安装 "+name,
                            "安装中...",
                            true);
                    binding.btnInstall.postDelayed(() -> {
                        installLoading.dismiss();
                    }, 20000l);
                    new Thread(() -> {

                        doCmd("cp " + finalSuPath + " /data/local/tmp/");
                        SystemClock.sleep(2000);
                        // doCmd("cd /data/local/tmp");
                        // SystemClock.sleep(1500);
                        doCmd("chmod 755 /data/local/tmp/mtk-su");
                        SystemClock.sleep(1500);

                        doCmd("cd " + "/data/local/tmp/");
                        SystemClock.sleep(1500);
                        doCmd("./mtk-su");
                        SystemClock.sleep(1500);
                        doCmd("mount -r -w -o remount -t ext4 /system");
                        SystemClock.sleep(1500);

                        doCmd("cp " + finalInputApkName + " /data/app");
                        SystemClock.sleep(5000);
                        // doCmd("cd /data/app", 2500);
                        SystemClock.sleep(1500);
                        doCmd("chmod 777 " + "/data/app/" + name);
                        SystemClock.sleep(1500);

                        ToastUtil.show("执行结束");
                    }).start();
                }
            });
            dialog.show(getActivity().getSupportFragmentManager(), "install");
        });
    }

    private void installApk() {

    }

    private void getTmpRoot() {


    }

    private void intiCmdInput(View view) {
        binding.etCmdInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.d(TAG, "onKey: actionId=" + actionId);
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String cmd = binding.etCmdInput.getText().toString();
                    if (!TextUtils.isEmpty(cmd) && mCmdListener != null) {
                        mCmdListener.onCmd(cmd);
                        binding.etCmdInput.setText("");
                    }
                }
                return true;
            }
        });

        binding.btnSendCmd.setOnClickListener(v -> {
            String cmd = binding.etCmdInput.getText().toString();
            if (!TextUtils.isEmpty(cmd) && mCmdListener != null) {
                mCmdListener.onCmd(cmd);
                binding.etCmdInput.setText("");
            }
        });
    }

    public void doCmd(String cmd, long delay) {
        binding.btnSendCmd.postDelayed(() -> {
            if (mCmdListener != null) {
                mCmdListener.onCmd(cmd);
            }
        }, delay);
    }

    public void doCmd(String cmd) {
        doCmd(cmd, 200);
    }

    private CommandActivity.OnCmdListener mCmdListener;

    public void setCmdListener(CommandActivity.OnCmdListener cmdListener) {
        mCmdListener = cmdListener;
    }
}